package com.shujia.login;

/*
    要实现的功能：
        1、用户的注册，登录，加上手机号验证功能  用户表的字段：id, name, password, phoneNum, create_time
        2、验证码使用redis存储，并设置60s过期时间，
        3、登录成功之后，实现案例2：Redis当作缓存，mysql查询案例
 */

import redis.clients.jedis.Jedis;
import utils.CodeTool;
import utils.MysqlTool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class LoginDemo {
    private static Scanner sc;
    private static Connection conn;
    private static Jedis jedis = new Jedis("192.168.21.150", 7000);

    public static void main(String[] args) {
        //创建键盘录入对象
        sc = new Scanner(System.in);
        //使用工具类获取数据库连接对象
        conn = MysqlTool.getConnection();

        init();

    }

    //用户初始进入界面
    public static void init(){
        System.out.println("==============|| 欢迎来到雷鹏程购物中心 ^_^ || ===================");
        int flag = login(); // 1、登录成功！ 2、登录失败  3、未注册
        if(flag==1){
            System.out.println("登录成功！！！");
            System.out.println("-------------------------------------------------------");

            System.out.println("1、详细信息查询 or 2、分类查询：");
            System.out.print("请选择您的查询方式: ");
            String choice = sc.nextLine();
            if("1".equals(choice)){
                System.out.print("请输入您要查询的商品: ");
                String goodsName = sc.nextLine();

                //机械革命（MECHREVO）极光Pro 15.6英寸12代酷睿i7游戏本笔记本电脑(i7-12650H 16G 512G RTX4060 165HZ 2.5K屏)
                findGoods(goodsName);
            }else if("2".equals(choice)){
                findGoods2();
            }


        }else if(flag==2){
            System.out.println("登录失败！！！");
        }else if(flag==3){
            regist();
        }
    }

    public static int login(){
        System.out.print("请输入您的账户名: ");
        String name = sc.nextLine();

        int a=0;

        boolean existUser = isExistUser(name);
        if(existUser){
            //用户存在的情况
            System.out.print("请输入您的密码: ");
            String password = sc.nextLine();

            //发送验证码
            System.out.print("请输入您的手机号: ");
            String phoneNum = sc.nextLine();
            //使用工具类发送验证码
            String code = CodeTool.sendCode(phoneNum);
            System.out.println("验证码已发送，请输入您收到的验证码: ");
            //将验证码写入到redis中
            setCodeRedis(code,name);
            String yzm = sc.nextLine();
            //269367
            //去redis中找是否有该验证码
            String s = jedis.get("sjcode" + name);
            if(s!=null){
                if(yzm.equals(code)){
                    try {
                        PreparedStatement ps = conn.prepareStatement("select * from users where name=? and password=?");
                        ps.setString(1,name);
                        ps.setString(2,password);
                        ResultSet resultSet = ps.executeQuery();
                        boolean flag = resultSet.next();
                        if(flag){
                            a=1;
                        }else {
                            a=2;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }else {
                    a=2;
                }
            }else {
                System.out.println("验证码已经过期");
                a=2;
            }
        }else {
            a=3;
        }

        return a;
    }

    //根据姓名判断用户是否存在
    public static boolean isExistUser(String username){

        boolean flag = false;
        try {
            PreparedStatement ps = conn.prepareStatement("select * from users where name=?");
            ps.setString(1,username);
            ResultSet resultSet = ps.executeQuery();
            flag = resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static void regist(){
        System.out.println("请注册用户！");
        System.out.print("请输入您的账户名: ");
        String newName = sc.nextLine();
        System.out.println("请输入您的密码: ");
        String password = sc.nextLine();
        System.out.println("请输入您的手机号: ");
        String phoneNum = sc.nextLine();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        int flag=0;

        try {
            PreparedStatement ps = conn.prepareStatement("insert into users(name,password,phoneNum,create_time) values(?,?,?,?)");
            ps.setString(1,newName);
            ps.setString(2,password);
            ps.setString(3,phoneNum);
            ps.setString(4,time);

            flag = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        try {
            System.out.println("注册中.....请稍后");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(flag==1){
            System.out.println("注册成功！");
        }else {
            System.out.println("注册失败！");
        }
    }

    //将验证码写入到redis中，并设置过期时间
    public static void setCodeRedis(String code,String username){

        jedis.set("sjcode"+username,code);
        jedis.expire("sjcode"+username,60);
//        jedis.close();
    }

    public static void findGoods(String goodsName){
        //先查询redis
        String info = jedis.get(goodsName);
        if(info!=null){
            System.out.println("******************* 这一步走的是redis查询 *******************");
            System.out.println(info);
        }else {
            System.out.println("******************* 这一步走的是mysql查询 *******************");
            //缓存中没有该数据
            try {
                PreparedStatement ps = conn.prepareStatement("select * from jd_goods where name=?");
                ps.setString(1,goodsName);
                ResultSet resultSet = ps.executeQuery();
                boolean next = resultSet.next();
                if(next){
                    String name = resultSet.getString(2);
                    String price = resultSet.getString(3);
                    String shop = resultSet.getString(4);
                    String commit = resultSet.getString(5);
                    String info2 = name+"| "+price+"| "+shop+"| "+commit;
                    System.out.println(info2);
                    //将结果放入到redis中并设置过期时间
                    jedis.set(name,info2);
                    jedis.expire(name,3600);
                }else {
                    System.out.println("商品不存在！！");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void findGoods2(){
        System.out.print("请选择您的商品大类:（手机 or 电脑）");
        String s = sc.nextLine();
        if("手机".equals(s)){
            System.out.print("请选择您的商品厂商: （小米 or OPPO）");
            String s1 = sc.nextLine();
            if("小米".equals(s1)){
                List<String> ids = jedis.lrange("手机:小米", 0, -1);
                findGoodsById(ids);
            }else if("OPPO".equals(s1)){
                List<String> ids = jedis.lrange("手机:OPPO", 0, -1);
                findGoodsById(ids);
            }
        }else if("电脑".equals(s)){
            System.out.println("请选择您的商品厂商: （联想 or 机械革命）");
            String s1 = sc.nextLine();
            if("联想".equals(s1)){
                List<String> ids = jedis.lrange("电脑:联想", 0, -1);
                findGoodsById(ids);
            }else if("机械革命".equals(s1)){
                List<String> ids = jedis.lrange("电脑:机械革命", 0, -1);
                findGoodsById(ids);
            }
        }

    }


    public static void findGoodsById(List<String> ids){
        try {
            PreparedStatement ps = conn.prepareStatement("select * from jd_goods where id=?");

            for (String id : ids) {
                ps.setString(1,id);
                ResultSet resultSet = ps.executeQuery();
                resultSet.next();
                String goodId = resultSet.getString(1);
                String name = resultSet.getString(2);
                String price = resultSet.getString(3);
                String shop = resultSet.getString(4);
                String commit = resultSet.getString(5);
                System.out.println(id+"| "+name+"| "+price+"| "+shop+"| "+commit);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
